package info.niwota.start;

import info.niwota.start.home.HomeAppLoader;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author qiangli
 * 
 */
public class UserFolderDialog {

	public static AlertDialog create(final Activity ctx, final String itemId,
			final String title) {
		final AlertDialog.Builder b = new AlertDialog.Builder(ctx);
		b.setTitle(title);
		b.setIcon(R.drawable.ic_dialog_menu_generic);
		b.setInverseBackgroundForced(true);
		//
		final MyListAdapter adapter = new MyListAdapter(ctx, itemId);

		b.setAdapter(adapter, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Intent ci = adapter.intentForPosition(which);
				if (ci != null) {
					ctx.startActivity(ci);
					dialog.dismiss();
					ctx.finish();
				}
			}
		});
		b.setCancelable(true);
		final AlertDialog d = b.create();
		return d;
	}

	private final static class MyListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		private List<ResourceInfo> mList;

		private Context context;

		private String itemId;

		public MyListAdapter(Context context, String itemId) {
			this.context = context;
			this.itemId = itemId;
			init();
		}

		private void init() {
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mList = new ArrayList<ResourceInfo>();
			HomeAppLoader.loadUserFolder(context, itemId, mList);
		}

		public Intent intentForPosition(int position) {
			if (mList == null) {
				return null;
			}
			ResourceInfo info = mList.get(position);
			return info.getIntent();
		}

		public int getCount() {
			return mList != null ? mList.size() : 0;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			if (convertView == null) {
				view = mInflater.inflate(R.layout.list_item, parent, false);
			} else {
				view = convertView;
			}
			bindView(view, mList.get(position));
			return view;
		}

		private final void bindView(View view, ResourceInfo info) {
			TextView text = (TextView) view.findViewById(R.id.line1);
			
			ImageView icon = (ImageView) view.findViewById(R.id.icon);
			text.setText(info.getTitle());
			icon.setImageDrawable(info.getIcon());
		}

	}
}
